using System.Runtime.InteropServices;
using Microsoft.SharePoint;

namespace Eneta.Portal.Deployment.Features.Eneta.Site.Lists
{
    [Guid("66d0f78d-be5b-4875-aaaf-655b1c954f31")]
    public class EnetaSiteEventReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web;
            if (properties.Feature.Parent is SPWeb)
                web = properties.Feature.Parent as SPWeb;
            else
                web = ((SPSite)properties.Feature.Parent).RootWeb;

            var list = web.Lists["Keywords"];

            if (HasField(web, "EnetaKeywords"))
            {
                var field = web.Fields["EnetaKeywords"] as SPFieldLookup;
                field.SchemaXml = field.SchemaXml.Replace(field.LookupList, list.ID.ToString());
                field.Update(true);
            }
            else
            {
                web.Fields.AddLookup("EnetaKeywords", list.ID, true);
                var field = web.Fields["EnetaKeywords"] as SPFieldLookup;
                field.LookupField = SPBuiltInFieldId.Title.ToString();
                field.Update(true);
                web.Update();
            }
            /*
            list = web.Lists["Regions"];

            if (HasField(web, "Offices"))
            {
                var field = web.Fields["Offices"] as SPFieldLookup;
                field.SchemaXml = field.SchemaXml.Replace(field.LookupList, list.ID.ToString());
                field.AllowMultipleValues = true;
                field.Update(true);
            }
            else
            {
                web.Fields.AddLookup("Offices", list.ID, true);
                var field = web.Fields["Offices"] as SPFieldLookup;
                field.LookupField = SPBuiltInFieldId.Title.ToString();
                field.AllowMultipleValues = true;
                field.Update(true);
                web.Update();
            }
             * */
        }

        public static bool HasField(SPWeb web, string fieldName)
        {
            foreach (SPField field in web.Fields)
            {
                if (field.InternalName == fieldName)
                {
                    return true;
                }
            }
            return false;
        }
    }
}